package com.ezbuy.common.factory;

import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;

public class SingletonFactory {

    //服务类 -> 实现对象的软引用,只有资源不足时,GC才会回收对象（一般的GC不会）
    private static Map<Class<?>, SoftReference<Object>> implMap = new HashMap<>();

    public static <T> T getInstance(Class<T> clazz) {
        SoftReference<Object> softReference = implMap.get(clazz);
        return (T) (softReference.get());
    }

    public static <T> void register(Class<T> clazz, T instance) {
        implMap.put(clazz, new SoftReference<Object>(instance));
    }

    public static <T> void unRegister(Class<T> clazz) {
        implMap.remove(clazz);
    }

}
